package com.yxzr.youyou;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.just.agentweb.AgentWeb;
import com.yxzr.youyou.adapter.CommentAdapter;
import com.yxzr.youyou.adapter.PictureRecyclerViewAdapter;
import com.yxzr.youyou.bean.CommentBean;
import com.yxzr.youyou.bean.MovieDetailBean;
import com.yxzr.youyou.retrofit.BaseObserver;
import com.yxzr.youyou.retrofit.RequestUtil;
import com.yxzr.youyou.utils.AppManager;
import com.yxzr.youyou.utils.HiddenAnimUtils;
import com.yxzr.youyou.utils.NullStringToEmptyAdapterFactory;
import com.yxzr.youyou.utils.RecyclerItemDecoration;
import com.yxzr.youyou.utils.ScreenUtils;
import com.yxzr.youyou.utils.SharedPreferencesHelper;
import com.yxzr.youyou.utils.StatusUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MoviePlayActivity extends AppCompatActivity {
    private TextView mMoviePlayName,mMoviePlayScore,mMoviePlayNum,mMovieCollect,mMoviePlayTopNum,mMoviePlayStepNum,mMoviePlayStime,
            mMoviePlayDirector,mMoviePlayPerformer,mMoviePlayAddress, mMoviePlayType,mMoviePlayPlot,mMoviePlayZuiXin,comment_tv_num;
    private LinearLayout liner_web;
    private LinearLayout movieplay_linear_collect,movieplay_linear_top,movieplay_linear_step;
    private AgentWeb mAgentWeb ;
    private RecyclerView mRecyclerView,mRecyclerViewComment;
    private RelativeLayout movieplay_rel_comment;
    private ImageView movie_img_back,mImageViewShow;
    private ImageView movieplay_img_collect,movieplay_img_topnum,movieplay_img_stepnum;
    private LinearLayout movieplay_linear;
    private CommentAdapter adapterComment;
    private List<MovieDetailBean.DataBean> list = new ArrayList<>();
    private List<CommentBean.DataBean> listComment = new ArrayList<>();
    private int index = 0;
    private int collectIndex = 0;
    private String url = "";
    private StatusUtils statusUtils;
    private SharedPreferencesHelper sp;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movieplay);
        AppManager.getInstance().addActivity(this); //添加到栈中
        url = getIntent().getStringExtra("url");
        list = (List<MovieDetailBean.DataBean>) getIntent().getSerializableExtra("bean");
        sp = new SharedPreferencesHelper(this,"logindata");
        statusUtils = new StatusUtils(this);
        Log.e("TAG","url:"+url);
        initView();
    }

    private void initView() {
        mMoviePlayName = findViewById(R.id.movieplay_tv_name);
        mMoviePlayScore = findViewById(R.id.movieplay_tv_score);
        mMoviePlayNum = findViewById(R.id.movieplay_tv_num);
        mMovieCollect = findViewById(R.id.movieplay_tv_collect);
        mMoviePlayTopNum = findViewById(R.id.movieplay_tv_topnum);
        mMoviePlayStepNum = findViewById(R.id.movieplay_tv_stepnum);
        mMoviePlayStime = findViewById(R.id.movieplay_tv_stime);
        mMoviePlayDirector = findViewById(R.id.movieplay_tv_director);
        mMoviePlayPerformer = findViewById(R.id.movieplay_tv_performer);
        mMoviePlayAddress = findViewById(R.id.movieplay_tv_address);
        mMoviePlayType = findViewById(R.id.movieplay_tv_type);
        mMoviePlayPlot = findViewById(R.id.movieplay_tv_plot);
        mMoviePlayZuiXin = findViewById(R.id.movieplay_tv_zuixin);
        mRecyclerView = findViewById(R.id.movieplay_rv);
        mImageViewShow = findViewById(R.id.movieplay_iv_show);
        movieplay_linear = findViewById(R.id.movieplay_linear);
        movie_img_back = findViewById(R.id.movie_img_back);
        liner_web = findViewById(R.id.liner_web);
        movieplay_linear_collect = findViewById(R.id.movieplay_linear_collect);
        movieplay_linear_top = findViewById(R.id.movieplay_linear_top);
        movieplay_linear_step = findViewById(R.id.movieplay_linear_step);
        movieplay_rel_comment = findViewById(R.id.movieplay_rel_comment);
        movieplay_img_collect = findViewById(R.id.movieplay_img_collect);
        movieplay_img_topnum = findViewById(R.id.movieplay_img_topnum);
        movieplay_img_stepnum = findViewById(R.id.movieplay_img_stepnum);
        mRecyclerViewComment = findViewById(R.id.comment_rv);
        comment_tv_num = findViewById(R.id.comment_tv_num);


        movie_img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) liner_web, new LinearLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .createAgentWeb()
                .ready()
                .go(url);

        movieplay_rel_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MoviePlayActivity.this, CommentActivity.class);
                intent.putExtra("bean", (Serializable) list);
                startActivity(intent);
            }
        });

        mMoviePlayName.setText(list.get(0).getTitle());
        mMoviePlayNum.setText(list.get(0).getHits());
        mMoviePlayTopNum.setText("顶("+list.get(0).getUp()+")");
        mMoviePlayStepNum.setText("踩("+list.get(0).getDown()+")");
        mMoviePlayScore.setText(list.get(0).getRating());
        mMoviePlayStime.setText(list.get(0).getYear());
        mMoviePlayDirector.setText(list.get(0).getDirectors());
        mMoviePlayPerformer.setText(list.get(0).getActors());
        mMoviePlayAddress.setText(list.get(0).getArea());
        mMoviePlayType.setText(list.get(0).getCtitle());
        mMoviePlayPlot.setText(list.get(0).getContent());
        mMoviePlayZuiXin.setText("最新"+list.get(0).getCtitle());
        comment_tv_num.setText("评论("+list.get(0).getCommentCount()+")");

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.addItemDecoration(new RecyclerItemDecoration(20,3));
        mRecyclerView.setAdapter(new PictureRecyclerViewAdapter(this,list.get(0).getZuixin()));
        mRecyclerView.setNestedScrollingEnabled(false);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerViewComment.setLayoutManager(linearLayoutManager);
        mRecyclerViewComment.addItemDecoration(new RecyclerItemDecoration(2,1));
        adapterComment = new CommentAdapter(this);
        mRecyclerViewComment.setAdapter(adapterComment);

        mImageViewShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (index == 0){
                    mImageViewShow.setImageResource(R.mipmap.movie_top);
                    index = 1;
                }else {
                    mImageViewShow.setImageResource(R.mipmap.movie_bottom);
                    index = 0;
                }
                movieplay_linear.measure(View.MeasureSpec.makeMeasureSpec(ScreenUtils.getScreenWidthPixels(MoviePlayActivity.this), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                HiddenAnimUtils.newInstance(MoviePlayActivity.this,movieplay_linear,mImageViewShow,movieplay_linear.getMeasuredHeight()+20).toggle();
            }
        });

        //收藏
        movieplay_linear_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (statusUtils.isLogin()){
                    if (collectIndex == 0){
                        initData();
                    }else {
                        closeCollect();
                    }
                }else {
                    statusUtils.toLoginActivity();
                }

            }
        });

        //顶
        movieplay_linear_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (statusUtils.isLogin()){
                    dingcai("1");
                }else {
                    statusUtils.toLoginActivity();
                }

            }
        });

        //踩
        movieplay_linear_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (statusUtils.isLogin()){
                    dingcai("2");
                }else {
                    statusUtils.toLoginActivity();
                }
            }
        });
        getCommentList();
        addPlay();
        isCollect();
        isDC();
    }

    private void initData(){
        RequestUtil.getInstence().API().favorites_add((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Toast.makeText(MoviePlayActivity.this,"收藏成功",Toast.LENGTH_LONG).show();

                        movieplay_img_collect.setImageResource(R.mipmap.movie_collect_select);
                        mMovieCollect.setText("取消收藏");

                        collectIndex = 1;
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void getCommentList(){
        RequestUtil.getInstence().API().getCommentList((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id(),"1")
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                        CommentBean bean = gson.fromJson(t,CommentBean.class);

                        if (bean.getData() != null){
                            listComment.clear();
                            adapterComment.clearList();
                            if (bean.getData().size() >= 3){
                                for (int i = 0;i < 3;i++){
                                    listComment.add(bean.getData().get(i));
                                }
                            }else if (bean.getData().size() < 3 && bean.getData().size() > 0){
                                for (int i = 0;i < bean.getData().size();i++){
                                    listComment.add(bean.getData().get(i));
                                }
                            }
                            adapterComment.addList(listComment);
                        }
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void closeCollect(){
        RequestUtil.getInstence().API().favorites_no((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Toast.makeText(MoviePlayActivity.this,"取消成功",Toast.LENGTH_LONG).show();

                        movieplay_img_collect.setImageResource(R.mipmap.movie_collect);
                        mMovieCollect.setText("收藏");

                        collectIndex = 0;
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void dingcai(String type){
        RequestUtil.getInstence().API().up((String) sp.getSharedPreference("token",""),type,list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Toast.makeText(MoviePlayActivity.this,"成功",Toast.LENGTH_LONG).show();

                        if ("1".equals(type)){
                            movieplay_img_topnum.setImageResource(R.mipmap.movie_zan_select);
                            mMoviePlayTopNum.setText("顶("+(Integer.parseInt(list.get(0).getUp()+1))+")");
                        }else {
                            movieplay_img_stepnum.setImageResource(R.mipmap.movie_nozan_select);
                            mMoviePlayStepNum.setText("踩("+(Integer.parseInt(list.get(0).getDown()+1))+")");
                        }

                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void isCollect(){
        RequestUtil.getInstence().API().is_favorites((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        collectIndex = 1;
                        movieplay_img_collect.setImageResource(R.mipmap.movie_collect_select);
                        mMovieCollect.setText("取消收藏");
                    }

                    @Override
                    protected void onFail(int error_code) {
                        collectIndex = 0;
                        movieplay_img_collect.setImageResource(R.mipmap.movie_collect);
                        mMovieCollect.setText("收藏");
                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }


    private void isDC(){
        RequestUtil.getInstence().API().is_up((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        movieplay_img_topnum.setImageResource(R.mipmap.movie_zan_select);
                    }

                    @Override
                    protected void onFail(int error_code) {
                        if (error_code == 201){
                            movieplay_img_stepnum.setImageResource(R.mipmap.movie_nozan_select);
                        }
                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void addPlay(){
        RequestUtil.getInstence().API().add_bofang((String) sp.getSharedPreference("token",""),list.get(0).getMovie_id())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {

                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getInstance().finishActivity(this); //从栈中移除
    }
}
